<!--
*@Author: QWP
*@Description: 综合预警
*@Date: 2024-07-08 09:51:28
-->
<template>
  <a-layout class="f-h-100 s-bg-white" >
    <u-collapsed-sider class="f-padding-6">
      <u-tree
        :treeData="resourceServeTree.tree[0].children"
        ref="treeRef"
        :showSearch="false"
        :field-names="{
          title: 'text',
          key: 'id',
          children: 'children',
        }"
        v-model:expandedKeys="treeExpandes"
        @select="(keys,{selected: bool, selectedNodes, node, event}) => {
          searchF.model.fkRegionId = node['code'];
          getSearch(1)
        }" />
    </u-collapsed-sider>

    <a-layout class="f-h-100 s-bg-white">
      <u-table-header>
        <u-form
          :model="searchF"
          :gutter="16"
          :elements="searchEl"
          class="f-w-auto"
          :isSearch="true"
          @formChange="getSearch(1)">
          <a-col>
            <a-space>
              <u-icon-button @click="getSearch(1)">查询</u-icon-button>
              <!-- <u-icon-button itype="export" @click="exportBtn">导出</u-icon-button> -->
            </a-space>
          </a-col>
          <a-col flex="1">
            <a-row justify="end">
              <a-space>
                <!-- <u-icon-button itype="add" @click="showEdit = true">新增</u-icon-button>
                <u-icon-button itype="edit" @click="showEdit = true">修改</u-icon-button>
                <u-icon-button itype="delete" @click="">删除 </u-icon-button> -->
                <template v-if="type == 'index'">
                  <!-- <u-icon-button @click="focusCancel(1)">关注企业 </u-icon-button> -->
                  <!-- <u-icon-button itype="delete" @click="focusCancel(0)">取消关注 </u-icon-button> -->
                </template>
              </a-space>
            </a-row>
          </a-col>
        </u-form>
      </u-table-header>
      <u-table-content>
        <u-table
          :columns="columns"
          :data="tabData"
          v-model:pagination="pagenation"
          :loading="loading"
          :scroll="{ y: useTableScroll() }"
          @onSelect="({ selectedRows }) => tabSelData = selectedRows"
          @onDblclick="(record) => {
            currentRow = record;
            showDispose = true
          }"
          @change="getSearch"></u-table>
      </u-table-content>
    </a-layout>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit v-model:open="showEdit"
    wrap-class-name="full-modal"
    :title="dialogTitle" />

  <!-- 预警处置 -->
  <WarningDispose v-model:open="showDispose"
    wrap-class-name="full-modal"
    title="当前预警处置" 
    :params="currentRow"
    @close="currentRow = {}"/>

  <!-- 现场视频 -->
  <LiveVideo v-model:open="showLive"
    title="" 
    width="800px"/>
  
  <!-- 企业信息详情 -->
  <u-dialog title="企业信息详情"
    width="100px"
    wrap-class-name="full-modal"
    v-model:open="showFirmDetial"
    :hideBtns="['submit']"
    @close="currentRow = {}">
    <FirmWarninGDetial :show="showFirmDetial" :params="currentRow"/>
  </u-dialog>
  
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave} from "vue-router";
import { _IFormEl } from "@/components/common/form/interface";
import { Row, Button, ColProps, FormItemProps, Space, TableColumnProps, TypographyTitle, Rate } from "ant-design-vue";
import { VideoCameraOutlined, ContainerOutlined, ThunderboltOutlined } from '@ant-design/icons-vue';
import { _IExtra } from '@/src/components/common/form/interface';
import { numberC, messageC } from '@/util/common'
import { formatAmt, } from '@/util/format.ts'
import dayjs from "dayjs";
import Edit from './Edit.vue'
import WarningDispose from './WarningDispose.vue'
import LiveVideo from './LiveVideo.vue'
import FirmWarninGDetial from '@/views/index/emergencyIndex/component/focusFirmWarning/FirmWarninGDetial.vue'
import { cloneDeep } from 'lodash'
import { regions } from '@/common/model/base'
import { levMainColor } from '@/views/index/emergencyIndex/data'
import { useTableScroll } from '@/hooks/useTable'
import { formatWarnLevel } from '@/views/oa/warning/sumWarning/utils.ts'
import UIconFont from '@/components/common/iconfont/IconFont.vue'
import * as sumWarningApi from '@/service/emergency/sumWarning'
import * as resourceServeTree from "@/service/resource/tree";

const props = defineProps<{
  type?: '', // index 首页的关注企业查看
}>()

const route = useRoute();
const router = useRouter();
const emits = defineEmits(['focusChange'])

const treeExpandes = ref(["fda30684-6473-4fb5-8cdb-0d6001a7dd15"]);

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: total => `共 ${total} 条`
})
const searchF = reactive({
  model: {
    keywords: null
  },
});
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '72px',
  wrapperCol: { span: 24 },
};
const searchEl: Array<_IFormEl> = [
  // { label: "预警类型", key: "yjlx", element: "select", col: { span: 3 }, formItemProps: formItemProps,
  //   componentProps: { 
  //     placeholder: '预警类型',
  //     options: [
  //       { label: '当前预警', value: '1'},
  //       { label: '历史预警', value: '2'},
  //     ]
  //   }
  // },
  // { label: "区域", key: "xzdq", element: "select", col: { span: 3 }, 
  //   formItemProps: { ...formItemProps, labelWidth: '40px' } ,
  //   componentProps: { placeholder: '区域',  options: regions }
  // },
  // { label: "企业类型", key: "qylx", element: "select", col: { span: 3 }, formItemProps: formItemProps,
  //   componentProps: { 
  //     placeholder: '企业类型', 
  //     options: [
  //       { label: '地下矿山', value: '1'},
  //       { label: '尾矿库', value: '2'},
  //     ] 
  //   }
  // },
  // { label: "关注状态", key: "gzzt", element: "select", col: { span: props.type != 'index' ? 0 : 3 }, formItemProps: formItemProps,
  //   componentProps: { 
  //     placeholder: '企业类型', allowClear: true,
  //     options: [
  //       { label: '关注', value: '1'},
  //       { label: '未关注', value: '2'},
  //     ] 
  //   }
  // },
  { label: "模糊查询", key: "keywords", element: "input", col: { span: 4 }, formItemProps: formItemProps,
    componentProps: { placeholder: '请输入企业名称' }
  },
];

// 列表
const currentRow = ref({})
const loading = ref<boolean>(false)
const tabSelData = ref<any[]>([])
const tabData = ref<any[]>([]);
let columns: Array<TableColumnProps> = reactive([
  { dataIndex: "ROW_ID", title: "序号", width: 50, align: 'center',},
  { dataIndex: "companyName", title: "企业名称", width: 200,
    customRender: ({ text, record }) => {
      return h(Row, { wrap: false}, () => [
      record.isAttention != '是' ? h('span') : h(UIconFont, { type: 'icon-a-guanzhu2' , style: { fontSize: '34px' } }),
        h('span', { 
          style: {color: '#1890ff', cursor: 'pointer'},
          onClick: () => {
            showFirmDetial.value = true;
            currentRow.value = record
          }
        }, text)
      ])
    }
  },
  { dataIndex: "address", title: "区域", width: 150 },
  { dataIndex: "companyType", title: "企业类型", width: 150 },
  { dataIndex: "warnSource", title: "预警来源", width: 150 },
  { dataIndex: "riskLevel", title: "预警等级", width: 150, align: 'center',
    customRender: ({text}) => {
      return formatWarnLevel(text)
    }
  },
  { dataIndex: "warnDate", title: "预警开始时间 ", width: 150 },
  // { dataIndex: "ts", title: "检查名称", width: 150 },
  // { dataIndex: "lxr", title: "检查时间", width: 150 },
  { dataIndex: "isAttention", title: "关注", width: 80, align: 'center',
    customRender: ({ text, index, record }) => {
      return h(Rate, { count: 1, value: text == '是' ? 1 : 0, 
        onChange: (value) => {
          focusCancel(text == '是' ? 0 : 1, record)
        } 
      }, () => '')
    }
  },
  // { dataIndex: "do", title: "视频", width: 80, align: 'center',
  //   customRender: ({}) => {
  //     return h(Button, { type: 'link', icon: h(VideoCameraOutlined), onClick: () => showLive.value = true  })
  //   }
  // },
  { dataIndex: "detial", title: "详情", width: 80, align: 'center',
    customRender: ({ record }) => {
      return h(Button, { type: 'link', icon: h(ContainerOutlined), onClick: () => {
        currentRow.value = record;
        showDispose.value = true;
      } })
    }
  },
]);

onMounted(() => {
  getSearch()
})

// 列表查询
const getSearch = async(current?: number) => {
  loading.value = true;
  try {
    if(current == 1) {
      pagenation.current = 1;
    }
    searchF.model.keywords = searchF.keywords;
    searchF.current = pagenation.current;
    searchF.size = pagenation.pageSize;
    const res = await sumWarningApi.getCompany(searchF)
    if(res.code == 0) {
      tabData.value = res.data.records || []
      pagenation.total = res.data.total
    }
  } catch (error) {}
  loading.value = false;
}

// type 1 取消、  0 关注
const focusCancel = async (type, record) => {
  loading.value = true;
  try {
    const res = await sumWarningApi.update_is_attention({
      isAttention: type,
      ids: record['mainId']
    })
    if(res.code == 0) {
      messageC(res.msg, "success");
      getSearch()
      emits('focusChange', record['mainId'])
    }
    else {
      messageC(res.msg, "warning");
    }
  } catch (error) {}
  loading.value = false;
}

// 编辑
let dialogTitle = ref<string>("隐患编辑")
let showEdit = ref<boolean>(false)
let showDispose = ref<boolean>(false)
let showLive = ref<boolean>(false)
let showFirmDetial = ref<boolean>(false)

// 导出
const exportBtn = async () => {
  try {
    loading.value = true;
    const res = await sumWarningApi.download({ ...searchF, size: -1,})
    loading.value = false;
  } catch (error) { }
  loading.value = false;
}
</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
